package lockDemo;

/**
 * @author Ajie
 * @date 8/18/21
 * @function
 *
 * 异常的时候
 * synchronized 会自动释放锁
 * ReentrantLock 不主动释放锁,在finally中一定释放锁
 */
public class Lock_Exception_Test {

    public static void main(String[] args) {
        syncExceptionReleaseLock();
    }

    private static void syncExceptionReleaseLock() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("run: thread A wait get lock");
                    synchronized (Lock_Exception_Test.class){
                        System.out.println("run: thread A get lock");
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){}
                        String a =null;
                        a.length();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println("A exception");
                while (true){
                    try {
                        Thread.sleep(10);
                    }catch (Exception e){}
                }
            }
        }).start();

        try {
            Thread.sleep(50);
        }catch (Exception e){}

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("run: thread B wait get lock");
                synchronized (Lock_Exception_Test.class){
                    System.out.println("run: thread B get lock");
                }
            }
        }).start();
    }
}
